package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZQH
 * @version 1.0
 * @date 2023/8/13 17:38
 */
@Slf4j
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 生成静态文件上传到minio中
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIo(ApArticle apArticle, String content) {
        //获取文章内容
        Template template = null;
        StringWriter out = new StringWriter();
        try {
            if (StringUtils.isNotBlank(content)){
                //通过freemarker生成文件
                template = configuration.getTemplate("article.ftl");
                //数据模型
                Map<String,Object> contentDateModel = new HashMap<>();
                contentDateModel.put("content", JSONArray.parseArray(content));
                //输出流
                template.process(contentDateModel,out);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
                //上传到minio
                ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
                String htmlFile = fileStorageService.uploadHtmlFile("", apArticle.getId()+".html", inputStream);
                //修改表中static_url内容
                apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                        .eq(ApArticle::getId,apArticle.getId())
                        .set(ApArticle::getStaticUrl,htmlFile));

    }
}
